﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Text;
using FlowCanvas.Nodes;
using UnityEditor;
using UnityEngine;
using UnityEngine.UI;
using XLua;

namespace Yoozoo.Framework.Managers
{
    public class YGUIProfiler : MonoBehaviour
    {
        // Start is called before the first frame update
        private static Stopwatch stopwatch;
        private static TimeSpan openTime;
        private static string openUI;
        private static string atlasNum;
        private static string atlas;
        private static Texture2D backgroundTexture;

        void Start()
        {
#if UNITY_EDITOR
            stopwatch = new Stopwatch();
            backgroundTexture =
                AssetDatabase.LoadAssetAtPath<Texture>("Assets/ResourcesAssets/UI/GUI/Common/frm_com_item_none.png") as Texture2D;
#endif
        }

        // Update is called once per frame
        void Update()
        {
            
        }

        private void OnGUI()
        {
            if (openTime!=default)
            {
                GUIStyle redStyle = new GUIStyle(GUI.skin.label);
                redStyle.normal.textColor = Color.red;
                GUILayout.Label(openUI,redStyle);
                GUILayout.Label(openTime.TotalMilliseconds.ToString("F2") + "毫秒",redStyle);
                GUILayout.Label("图集数量："+atlasNum,redStyle);
                GUILayout.Label(atlas,redStyle);
            }
        }

        [LuaCallCSharp]
        public static void OpenUI(string uiName)
        {
            if (stopwatch!=null)
            {
                stopwatch.Reset();
                stopwatch.Start();
            }
        }
        
        [LuaCallCSharp]
        public static void show(string uiName,GameObject gameObject)
        {
            if (stopwatch!=null)
            {
                stopwatch.Stop();
                openUI = uiName;
                openTime = stopwatch.Elapsed;
#if UNITY_EDITOR
                GetAtlas(gameObject);
#endif
            }
  
        }
#if UNITY_EDITOR
        private static void GetAtlas(GameObject gameObject)
        {
            var images = gameObject.GetComponentsInChildren<Image>(true);
            var spriteAtlasMap = new Dictionary<string, AtlasInfo>();
            foreach (var image in images)
            {
                if(image.sprite == null) continue;
                string spritePath = AssetDatabase.GetAssetPath(image.sprite);
                string atlasPath = GetSpriteAtlasPath(spritePath);
                if (!string.IsNullOrEmpty(atlasPath))
                {
                    if (!spriteAtlasMap.TryGetValue(atlasPath, out var atlasInfo))
                    {
                        atlasInfo = new AtlasInfo
                        {
                            AtlasPath = atlasPath
                        };
                        spriteAtlasMap[atlasPath] = atlasInfo;
                    }

                    string objectPath = GetPath(image.transform);
                    atlasInfo.Add(spritePath, objectPath);
                }
            }
            StringBuilder stringbuilder = new StringBuilder();
            int index = 1;
            foreach (var atlasInfo in spriteAtlasMap.Values)
            {
                stringbuilder.AppendFormat("图集{0}: {1}\n", index, atlasInfo.AtlasPath);
                index++;
            }

            atlas = stringbuilder.ToString();
        }
        private static string GetSpriteAtlasPath(string spritePath)
        {
            if (string.IsNullOrEmpty(spritePath))
                return "";
            
            string directory = Path.GetDirectoryName(spritePath);
            if (directory == null)
                return "";

            if (!directory.Contains("\\UI\\GUI\\"))
                return "";

            if (directory.Contains("\\icon\\"))
                return directory;

            var directoryInfo = new DirectoryInfo(directory);
            string atlasPath = directory;
            while (directoryInfo != null && directoryInfo.Name != "GUI" )
            {
                atlasPath = directoryInfo.FullName;
                atlasPath = atlasPath.Substring(atlasPath.IndexOf("Assets"));
                directoryInfo = directoryInfo.Parent;
            }

            return atlasPath;
        }
        private static string GetPath(Transform t)
        {
            var path = t.name;
            while (t.parent != null)
            {
                path = t.parent.name + "/" + path;
                t = t.parent;
            }

            return path;
        }
        private class AtlasInfo
        {
            public string AtlasPath;

            public List<SpriteInfo> SpriteInfos = new List<SpriteInfo>();

            public void Add(string spritePath, string objectPath)
            {
                var spriteInfo = new SpriteInfo
                {
                    SpritePath = spritePath,
                    ObjectPath = objectPath
                };
                SpriteInfos.Add(spriteInfo);
            }
        }
        public class SpriteInfo
        {
            public string SpritePath;

            public string ObjectPath;
        }
#endif
        #if UNITY_EDITOR
        [MenuItem(@"GTATools/UI/UI图集引用工具", false, 150)]
        public static void ConvertText()
        {
            GameObject gameObject = new GameObject("YGUIProfiler");
            gameObject.AddComponent<YGUIProfiler>();
        }
        #endif
    }
    
}

